package net.istore.market.dao;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

public abstract class AbstractDAO {

	@Autowired
	protected SessionFactory sessionFactory;


    public <T> T persistEntity(T entity) {
        sessionFactory.getCurrentSession().persist(entity);
        return entity;
    }

    public <T> T getEntity(Class<T> clazz,long id) {
        return (T) sessionFactory.getCurrentSession().get(clazz, id);
    }

    public <T> List<T> getEntities(Class<T> clazz, int from, int to) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(clazz);

        criteria.setFirstResult(from);
        criteria.setMaxResults(to);

        return criteria.list();
    }

    public <T> T remove(Class<T> clazz, long id) {
        T forRemove = getEntity(clazz, id);
        sessionFactory.getCurrentSession().delete(forRemove);
        return forRemove;
    }
}
